package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面，实现公共字段自动填充处理逻辑
 */
@Slf4j
@Component
@Aspect
public class AutoFillAspect {

    @Before("@annotation(com.sky.anno.AutoFill)")
    public void doBefore(JoinPoint joinPoint) {
        // 1.获取方法对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 2.获取方法上的注解
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        // 3.获取方法的参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];
        try {
            // 4.判断注解的属性值 如果是insert 就补充四个字段
            if (annotation.value() == OperationType.INSERT) {
                // 获取set方法
                Method setCreateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setCreateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setCreateTime.invoke(arg, LocalDateTime.now());
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setCreateUser.invoke(arg, BaseContext.getCurrentId());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            }else if (annotation.value() == OperationType.UPDATE) {
                // 5.如果是update 就补充两个字段
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            }
        }catch (Exception e){
            throw new RuntimeException();
        }
    }
}
